<?php
// 【最终完整版】m-merchant/oder_data.php

header('Content-Type: application/json; charset=utf-8');

function verify_token($token) {
    $secret_key = 'kkcc.vip-is-the-best-!@#$%';
    if (!$token) return null; $token_parts = explode('.', $token); if (count($token_parts) !== 3) return null; list($h, $p, $s) = $token_parts;
    $sig = base64_decode(str_replace(['-','_'],['+','/'], $s)); $exp_sig = hash_hmac('sha256', $h.".".$p, $secret_key, true);
    if (!hash_equals($exp_sig, $sig)) return null; $payload = json_decode(base64_decode(str_replace(['-','_'],['+','/'], $p)), true);
    if ($payload === null || ($payload['exp']??0) < time()) return null; return $payload['data'];
}
function get_authorization_header() {
    if (isset($_SERVER['Authorization'])) return trim($_SERVER["Authorization"]); if (isset($_SERVER['HTTP_AUTHORIZATION'])) return trim($_SERVER["HTTP_AUTHORIZATION"]);
    if (function_exists('getallheaders')) { $h = getallheaders(); if (isset($h['Authorization'])) return trim($h['Authorization']); } return null;
}
function force_rename_check($con, $user_data) {
    if (!$user_data || !isset($user_data['proxy_acc'])) { http_response_code(401); echo json_encode(['status' => -99, 'msg' => '登录失效']); exit(); }
    $proxy_acc_safe = mysqli_real_escape_string($con, $user_data['proxy_acc']);
    $sql = "SELECT proxy_rename_sta, cr_time FROM proxy WHERE proxy_acc = '$proxy_acc_safe'"; $result = mysqli_query($con, $sql);
    if ($result && $row = mysqli_fetch_assoc($result)) {
        if ($row['proxy_rename_sta'] == 0 && (time() - (int)$row['cr_time']) > (3 * 24 * 60 * 60)) {
            http_response_code(403); echo json_encode(['status' => -10, 'msg' => '注册超3天未实名，请先认证']); exit();
        }
    } else { http_response_code(401); echo json_encode(['status' => -99, 'msg' => '无法验证用户']); exit(); }
}

$user_data = verify_token(str_replace('Bearer ', '', get_authorization_header()));
if ($user_data === null) { http_response_code(401); echo json_encode(['status' => -99, 'msg' => '登录失效或Token无效']); exit(); }

include_once("../untils/conn.php");
mysqli_query($con, "set names utf8");
force_rename_check($con, $user_data);

$current_proxy_id = (int)$user_data['proxy_id'];
$keyword = $_POST['keyword'] ?? '';
$scope = $_POST['scope'] ?? 'self';
$proxy_ids_to_query = [$current_proxy_id];
if ($scope === 'all') {
    $sub_query = "SELECT proxy_id FROM proxy WHERE proxy_upid = '{$current_proxy_id}'";
    $sub_res = mysqli_query($con, $sub_query);
    if ($sub_res) { while ($sub_row = mysqli_fetch_assoc($sub_res)) { $proxy_ids_to_query[] = (int)$sub_row['proxy_id']; } }
}
$proxy_ids_str = implode(',', $proxy_ids_to_query);
$accounts_map_sql = "SELECT proxy_id, proxy_acc, proxy_name FROM proxy WHERE proxy_id IN ({$proxy_ids_str})";
$res_accounts = mysqli_query($con, $accounts_map_sql);
$proxy_accounts_map = [];
if($res_accounts) { while($row_acc = mysqli_fetch_assoc($res_accounts)) { $proxy_accounts_map[$row_acc['proxy_id']] = !empty($row_acc['proxy_name']) ? $row_acc['proxy_name'] : $row_acc['proxy_acc']; } }

$sql = "SELECT * FROM oder WHERE proxy_id IN ({$proxy_ids_str})";
if (!empty($keyword)) {
    $keyword_safe = mysqli_real_escape_string($con, $keyword);
    $sql .= " AND (name LIKE '%{$keyword_safe}%' OR phone LIKE '%{$keyword_safe}%' OR oderid LIKE '%{$keyword_safe}%')";
}
$sql .= " ORDER BY id DESC LIMIT 200";
$result = mysqli_query($con, $sql);
$data = [];
if ($result) {
    while($row = mysqli_fetch_assoc($result)) {
        $proxy_id = $row['proxy_id'];
        $data[] = [
            'order_id' => $row['oderid'], 'goods_name' => $row['goods'], 'agent_name' => $proxy_accounts_map[$proxy_id] ?? '未知代理',
            'name' => $row['name'], 'phone' => $row['phone'], 'card_sta' => $row['card_sta'], 'order_sta' => $row['status'],
            'notes' => $row['beizhu'], 'order_time' => date('Y-m-d H:i:s', $row['time']), 'update_time' => $row['update_time'],
            'id_card' => substr_replace($row['uid'], '********', 6, 8),
            'address' => $row['sf'] . $row['city'] . $row['xian'] . $row['dizhi'],
            'logistics_id' => $row['wlord'], 'logistics_company' => $row['wlgs'],
        ];
    }
}
echo json_encode(['status' => 0, 'data' => $data]);
mysqli_close($con);
?>